﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;
using System.Net.Mail;

namespace ERPStore.Services
{
	public class EmailerService : ERPStore.Services.IEmailerService
	{
		public EmailerService(Logging.ILogger logger)
		{
			this.Logger = logger;
		}

		protected Logging.ILogger Logger { get; set; }

		public DateTime Ping()
		{
			return DateTime.Now;
		}

		public virtual void Send(Models.MailMessage mailMessage)
		{
			Send(mailMessage, null);
		}

		public virtual void Send(ERPStore.Models.MailMessage mailMessage, DateTime? scheduledDate)
		{
			var message = (System.Net.Mail.MailMessage)mailMessage;
			message.Headers.Add("X-Mailer", "ERPStore.EmailerService");
			var htmlView = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, "text/html");
			htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
			message.AlternateViews.Add(htmlView);

			Send(message);
		}

		public virtual void Send(System.Net.Mail.MailMessage message)
		{
			try
			{
				using (var client = GetCurrentSmtpClient())
				{
					client.Send(message);
				}
			}
			catch (Exception ex)
			{
				if (ex.Message.Equals("The SMTP host was not specified", StringComparison.InvariantCultureIgnoreCase))
				{
					return;
				}
				Logger.Error(ex);
			}
		}

		/// <summary>
		/// Gets the current SMTP client.
		/// </summary>
		/// <value>The current SMTP client.</value>
		protected virtual System.Net.Mail.SmtpClient GetCurrentSmtpClient()
		{
			var client = new System.Net.Mail.SmtpClient();
			client.SendCompleted += new SendCompletedEventHandler(m_SmtpClient_SendCompleted);

			// For Tests
			if (client.DeliveryMethod == System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory
				&& client.PickupDirectoryLocation == @".\")
			{
				var path = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
				path = System.IO.Path.Combine(path, "emails");
				if (!System.IO.Directory.Exists(path))
				{
					System.IO.Directory.CreateDirectory(path);
				}
				client.PickupDirectoryLocation = path;
			}

			return client;
		}

		void m_SmtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			if (e.Error != null)
			{
				Logger.Error(e.Error);
			}
		}

	}
}
